//
//  HLWelcomeController.swift
//  weibo-snh
//
//  Created by 黄力 on 15/12/17.
//  Copyright © 2015年 HLTest. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit

class HLWelcomeController: UIViewController {
    
    //更换根视图
    override func loadView() {
        view = backImageView
    }

    override func viewDidLoad() {
        
        super.viewDidLoad()
        //设置界面
        setupUI()
    }
    
    //要在该方法中执行动画,viewdidLoad方法中view的frame还没设置完成
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        startAnimation()
    }

    //设置界面
    private func setupUI() {
        //添加子控件
        view.addSubview(iconView)
        view.addSubview(titleLabel)
        //设置约束
        //头像视图
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.centerY.equalTo(view.snp_bottom).offset(-200)
            make.size.equalTo(CGSize(width: 90, height: 90))
        }
        //文字视图
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(iconView.snp_centerX)
            make.top.equalTo(iconView.snp_bottom).offset(15)
        }
        //隐藏文字
        titleLabel.alpha = 0
    }
    
    //动画
    private func startAnimation() {
        //修改头像视图的约束,修改的约束并不会立即执行
        iconView.snp_updateConstraints { (make) -> Void in
            make.centerY.equalTo(view.snp_bottom).offset(-500)
        }
        //动画效果
        UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 9.8, initialSpringVelocity: 0.8, options: [], animations: { () -> Void in
            //调用该方法才会立即更新约束
            self.view.layoutIfNeeded()
            }) { (_) -> Void in
                //出现文字的动画
                UIView.animateWithDuration(1.5, animations: { () -> Void in
                    self.titleLabel.alpha = 1
                    }, completion: { (_) -> Void in
                        //完成所有动画后发送通知改变根控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(MainWindowRootControllerChangeNotification, object: "GOTOMainController")
                })
        }
    }
    
    //背景图片
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage(named: "ad_background"))
    //头像
    private lazy var iconView: UIImageView = {
       let imageView = UIImageView()
        //设置图片
        imageView.sd_setImageWithURL(NSURL(string: HLUserAccountViewModel().userImageStr ?? ""), placeholderImage: UIImage(named: "avatar_default_big"))
        //设置图片圆角
        imageView.layer.cornerRadius = 45
        //设置剪切以外的部分不显示
        imageView.layer.masksToBounds = true
        return imageView
    }()
    //文字
    private lazy var titleLabel: UILabel = UILabel(title: (HLUserAccountViewModel().userName ?? "") + " 欢迎回来", titleColor: UIColor.lightGrayColor(), titleFont: 15)


}
